package com.whlilong.jxc.filemanager.editor;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.IJobChangeEvent;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.core.runtime.jobs.JobChangeAdapter;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeColumn;

import com.whlilong.jxc.db.DbManager;
import com.whlilong.jxc.dialog.DepartInfoCreate;
import com.whlilong.jxc.editor.support.DepartInfoEditorSupport;
import com.whlilong.jxc.listener.IEditorListener;
import com.whlilong.jxc.model.Depart;
import com.whlilong.jxc.print.IconSource;
import com.whlilong.jxc.print.PDocument;
import com.whlilong.jxc.print.PHLine;
import com.whlilong.jxc.print.PTableBoxProvider;
import com.whlilong.jxc.print.PTextBox;
import com.whlilong.jxc.print.PVSpace;
import com.whlilong.jxc.print.PrintPreview;
import com.whlilong.jxc.print.SWTPTable;
import com.whlilong.jxc.service.editor.IEditorService;
import com.whlilong.jxc.sys.ExtentionInfo;
import com.whlilong.jxc.sys.SetTableColColorListener;
import com.whlilong.jxc.treemodel.DepartInfoTreeChildren;
import com.whlilong.jxc.treemodel.DepartInfoTreeParent;
import com.whlilong.jxc.ui.provider.DepartInfoContentProvider;
import com.whlilong.jxc.ui.provider.DepartInfoLabelProvider;
import com.whlilong.jxc.ui.provider.DepartInfoTreeContentProvider;
import com.whlilong.jxc.ui.provider.DepartInfoTreeLabelProvider;
import com.whlilong.jxc.ui.sorter.DepartInfoSorter;

/**
 * 部门信息编辑器
 * 
 * @author sjy
 * 
 */
public class DepartinfoEditor extends AbstractEditor implements IEditorService,
		IEditorListener {
	private Table table;
	protected ExtentionInfo extentionInfo = null;
	private Label infoLabel;
	private Label departNoLabel;
	private Text departNoText;
	private Label departNameLabel;
	private Text departNameText;
	private Button findBt;
	protected String departId;
	protected String departName;

	private List<Depart> list = new ArrayList<Depart>();
	private Shell shell = null;
	private boolean isSave = true;

	public DepartinfoEditor() {
		// TODO Auto-generated constructor stub
	}

	@Override
	public Control createGroupText(Composite parent) {

		Composite container = new Composite(parent, SWT.NONE);
		final GridLayout gl = new GridLayout(2, false);
		container.setLayout(gl);
		createTreeViewer(container);
		createTableViewer(container);

		return container;
	}

	private void createTreeViewer(Composite parent) {
		// TODO Auto-generated method stub
		treeViewer = new TreeViewer(parent, SWT.BORDER | SWT.V_SCROLL
				| SWT.FULL_SELECTION);
		treeViewer.setUseHashlookup(true);

		GridData gd = new GridData();
		gd.verticalAlignment = SWT.TOP;
		final Tree tree = treeViewer.getTree();
		tree.setLayoutData(new GridData(GridData.FILL_VERTICAL));
		final TreeColumn category = new TreeColumn(tree, SWT.LEFT);
		category.setText("所有部门");
		category.setWidth(100);

		treeViewer.setContentProvider(new DepartInfoTreeContentProvider());
		treeViewer.setLabelProvider(new DepartInfoTreeLabelProvider());
		treeViewer.setInput(extentionInfo.getInstance().getDepartTreeInfo());

		tree.setHeaderVisible(true);
		tree.setLinesVisible(true);

		treeViewer.expandToLevel(2);

		treeViewer.addSelectionChangedListener(new ISelectionChangedListener() {

			@Override
			public void selectionChanged(SelectionChangedEvent event) {
				// TODO Auto-generated method stub
				IStructuredSelection selection = (IStructuredSelection) event
						.getSelection();
				if (selection.getFirstElement() instanceof DepartInfoTreeChildren) {
					DepartInfoTreeChildren ktc = (DepartInfoTreeChildren) selection
							.getFirstElement();
					String id = ktc.getDepart().getDepartid();
					tableViewer.getTable().clearAll();
					tableViewer.setInput(getDepartInfo(id, null));
				}
				if (selection.getFirstElement() instanceof DepartInfoTreeParent) {
					initial();
					tableViewer.getTable().clearAll();
					tableViewer.setInput(list);
				}

			}
		});

	}

	private void initial() {
		// TODO Auto-generated method stub
		infoLabel.setForeground(Display.getCurrent().getSystemColor(
				SWT.COLOR_BLUE));
		infoLabel.setText("添加，删除，查询相关数据。。。");
		list = getDepartInfo(null, null);
	}

	protected List getDepartInfo(String id, String name) {
		List<Depart> newList = new ArrayList<Depart>();
		int[] idBuffer = { 0 };
		int[] idBuffer2 = { 0, 1 };
		Object[] idObject = { id };
		Object[] nameObject = { name };
		Object[] object = { id, name };
		if (id == null && name == null) {
			newList = (List) DbManager.getInstance().search(
					"com.whlilong.jxc.sys.getdepartinfo");
		} else if (id != null && name == null) {
			newList = (List) DbManager.getInstance().search(
					"com.whlilong.jxc.editor.getDepartInfo.getDepartid",
					idBuffer, idObject);
		} else if (id == null && name != null) {
			newList = (List) DbManager.getInstance().search(
					"com.whlilong.jxc.editor.getDepartInfo.getDepartname",
					idBuffer, nameObject);
		} else {
			newList = (List) DbManager.getInstance().search(
					"com.whlilong.jxc.editor.getDepartInfo.getDepart",
					idBuffer2, object);
		}
		return list = newList;
	}

	private void createTableViewer(Composite parent) {
		// TODO Auto-generated method stub
		Composite composite = new Composite(parent, SWT.NONE);
		GridLayout gl = new GridLayout(4, false);
		composite.setLayout(gl);
		composite.setLayoutData(new GridData(GridData.FILL_BOTH));

		infoLabel = new Label(composite, SWT.NONE);
		GridData gd = new GridData(GridData.FILL_HORIZONTAL);
		gd.heightHint = 20;
		gd.horizontalSpan = 4;
		infoLabel.setLayoutData(gd);

		gd = new GridData();
		gd.widthHint = 100;
		gd.heightHint = 20;
		departNoLabel = new Label(composite, SWT.RIGHT);
		departNoLabel.setText("部门编号：");
		departNoLabel.setLayoutData(gd);
		departNoText = new Text(composite, SWT.BORDER);
		departNoText.setLayoutData(gd);

		departNameLabel = new Label(composite, SWT.RIGHT);
		departNameLabel.setText("部门名称：");
		departNameLabel.setLayoutData(gd);
		departNameText = new Text(composite, SWT.BORDER);
		departNameText.setLayoutData(gd);

		findBt = new Button(composite, SWT.NONE);
		findBt.setText("查询F7");
		findBt.setLayoutData(gd);
		findBt.addMouseListener(new MouseAdapter() {

			@Override
			public void mouseDown(MouseEvent e) {
				// TODO Auto-generated method stub
				departId = departNoText.getText();
				departName = departNameText.getText();
				find(departId, departName);
			}

		});

		tableViewer = new TableViewer(composite, SWT.BORDER | SWT.H_SCROLL
				| SWT.FULL_SELECTION);
		tableViewer.setUseHashlookup(true);

		gd = new GridData(GridData.FILL_BOTH);
		gd.horizontalSpan = 4;
		table = tableViewer.getTable();
		table.setLayoutData(gd);
		table.setToolTipText("点击单元格对数据进行修改！");
		// 设置行高
		table.addListener(SWT.MeasureItem, new Listener() {
			public void handleEvent(Event event) {
				event.height = 20;
			}
		});

		DepartInfoEditorSupport editingSupport = new DepartInfoEditorSupport(
				tableViewer, 1, this);
		createColumn("ID", DepartInfoSorter.ID_ASC, DepartInfoSorter.ID_DESC,
				editingSupport);

		editingSupport = new DepartInfoEditorSupport(tableViewer, 2, this);
		createColumn("部门编号", DepartInfoSorter.departId_ASC,
				DepartInfoSorter.departId_DESC, editingSupport);
		manager.addITextKeyChangeListener(editingSupport);
		editingSupport = new DepartInfoEditorSupport(tableViewer, 3, this);
		createColumn("部门名称", DepartInfoSorter.departName_ASC,
				DepartInfoSorter.departName_DESC, editingSupport);
		manager.addITextKeyChangeListener(editingSupport);

		table.setHeaderVisible(true);
		table.setLinesVisible(true);

		// initial the tabelViewer
		tableViewer.setContentProvider(new DepartInfoContentProvider());
		tableViewer.setLabelProvider(new DepartInfoLabelProvider());
		initial();
		tableViewer.setInput(list);
		table.addListener(SWT.EraseItem, new SetTableColColorListener(table));

		table.select(0);
		table.setFocus();

	}

	@Override
	public void setFocus() {
		// TODO Auto-generated method stub

	}

	@Override
	public void addInfo() {
		// TODO Auto-generated method stub

	}

	@Override
	public void create() {
		Shell subshell = new Shell(shell, SWT.DIALOG_TRIM);
		DepartInfoCreate sb = new DepartInfoCreate(subshell, tableViewer);
		sb.open();
		if (!sb.isCacel()) {
			list = sb.getList();
			tableViewer.setInput(list);
			save();

		} else {
			list = (List) tableViewer.getInput();
		}
		infoLabel.setText("提示：添加新数据后请点击保存来更新数据！");
		tableViewer.getTable().select(list.size() - 1);
	}

	@Override
	public void delete() {
		IStructuredSelection selection = (IStructuredSelection) tableViewer
				.getSelection();
		Depart depart = (Depart) selection.getFirstElement();
		if (!selection.isEmpty()) {
			if (MessageDialog.openConfirm(null, "提示", "你确定删除数据吗？")) {
				delete(depart);
			}
		} else {
			MessageDialog.openConfirm(null, "提示", "请从表格中选择一行数据进行删除！");
		}
	}
	
	private void delete(Depart depart) {
		// TODO Auto-generated method stub
		String id = depart.getDepartid();
		if (!id.isEmpty()) {
			int[] idBuffer = { 0 };
			Object[] idObject = { id };
			List result = (List) DbManager.getInstance().search(
					"com.whlilong.jxc.editor.getDepartInfo.getDepartid", idBuffer, idObject);
			Depart dpt = (Depart) result.get(0);
			DbManager.getInstance().delete(dpt);
		}
		refresh();
	}

	@Override
	public void print() {
		final PDocument doc = new PDocument("print");

		PTextBox t;

		t = new PTextBox(doc);

		t.setText("武汉立隆客商信息");

		new PVSpace(doc, 0.5);
		new PHLine(doc, 0.02, SWT.COLOR_RED);
		new PVSpace(doc, 0.5);

		// create the table
		SWTPTable swttable = new SWTPTable(doc);
		swttable.setTable(table);
		swttable.setBoxProvider(new PTableBoxProvider());
		
		PrintPreview pr = new PrintPreview(null, "信息打印", IconSource
				.getImage("print"), doc);
		pr.onPrint();
	}

	@Override
	public void refresh() {
		initial();
		treeViewer.setInput(extentionInfo.getInstance().getDepartTreeInfo());
		treeViewer.expandToLevel(2);
		tableViewer.setInput(list);

	}

	@Override
	public void save() {
		if (!isSave) {
			MessageDialog.openWarning(null, "提示", "数据不能保存！");
			return;
		}
		manager.notifyListener();
		Iterator data = list.iterator();
		if (!data.hasNext()) {
			MessageDialog.openWarning(null, "提示", "没有需要保存的数据！");
			return;
		}

		Job job = new Job("正在保存数据。。。") {
			@Override
			protected IStatus run(IProgressMonitor monitor) {
				// TODO Auto-generated method stub
				monitor.beginTask("正在保存数据。。。", IProgressMonitor.UNKNOWN);
				for (int i = 0; i < list.size(); i++) {
					int id = list.get(i).getId();
					int[] idBuffer = { 0 };
					Object[] idObject = { id };
					List result = (List) DbManager.getInstance().search(
							"com.whlilong.jxc.editor.getDepartInfo.getId", idBuffer,
							idObject);
					if (result.size() > 0) {
						String departName = list.get(i).getDepartname();
						String departId = list.get(i).getDepartid();
						if (departId != null && !departId.equals("") && departName != null
								&& !departName.equals("")) {
							int count = 0;
							Depart k = (Depart) result.get(0);
							k.setId(id);
							k.setDepartid(departId);
							k
									.setDepartname(list.get(i)
											.getDepartname());
							monitor.worked(1);
							DbManager.getInstance().update(k);
						} else {
							return Status.CANCEL_STATUS;
						}

					} else {
						String departName = list.get(i).getDepartname();
						String departId = list.get(i).getDepartid();
						if (departId != null && !departId.equals("") && departName != null
								&& !departName.equals("")) {
							Depart ks = new Depart();
							ks.setId(id);
							ks.setDepartid(departId);
							ks.setDepartname(list.get(i)
									.getDepartname());
							DbManager.getInstance().insert(ks);
						} else {

							return Status.CANCEL_STATUS;
						}

					}
				}
				monitor.done();
				return Status.OK_STATUS;
			}

		};
		job.addJobChangeListener(new JobChangeAdapter() {
			public void done(IJobChangeEvent event) {
				final boolean isSuccess = event.getResult().isOK();
				Display.getDefault().asyncExec(new Runnable() {
					public void run() {
						if (isSuccess) {

							MessageDialog.openInformation(null, "提示",
									"数据已经成功保存！");
							treeViewer.setInput(extentionInfo.getInstance()
									.getDepartTreeInfo());
							treeViewer.refresh();
							treeViewer.expandToLevel(2);

						} else
							MessageDialog.openError(null, "错误", "编号或名称为空，数据保存失败！");
					}
				});
			}
		});
		job.setUser(false);
		job.setPriority(Job.SHORT);
		job.schedule();
	
	}

	@Override
	public void search() {
		departId = departNoText.getText();
		departName = departNameText.getText();
		find(departId, departName);
	}
	private void find(String id, String name) {
		// TODO Auto-generated method stub
		if ((id == null || id.equals("")) && (name == null || name.equals(""))) {
			tableViewer.setInput(getDepartInfo(null, null));
		} else if ((id != null || !id.equals(""))
				&& (name == null || name.equals(""))) {
			tableViewer.setInput(getDepartInfo(id, null));
		} else if ((id == null || id.equals(""))
				&& (name != null || !name.equals(""))) {
			tableViewer.setInput(getDepartInfo(null, name));
		} else {
			tableViewer.setInput(getDepartInfo(id, name));
		}
	}

	@Override
	public void searchByCondition() {
		search();
	}

	@Override
	public List getList() {
		// TODO Auto-generated method stub
		return this.list;
	}

	@Override
	public void noticeFault(String message) {
		infoLabel.setForeground(Display.getCurrent().getSystemColor(
				SWT.COLOR_RED));
		infoLabel.setText(message);
		this.isSave = false;
	}

	@Override
	public void noticeSuccess() {
		infoLabel.setText("");
		this.isSave = true;
	}

	@Override
	public void preprint() {
		// TODO Auto-generated method stub
		final PDocument doc = new PDocument("print");

		PTextBox t;

		t = new PTextBox(doc);

		t.setText("武汉立隆客商信息");

		new PVSpace(doc, 0.5);
		new PHLine(doc, 0.02, SWT.COLOR_RED);
		new PVSpace(doc, 0.5);

		// create the table
		SWTPTable swttable = new SWTPTable(doc);
		swttable.setTable(table);
		swttable.setBoxProvider(new PTableBoxProvider());
		
		PrintPreview pr = new PrintPreview(null, "信息打印", IconSource
				.getImage("print"), doc);
		pr.open();
	}
}
